package com.tjp.eight.utils;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/3/3.
 */

public class TimeCountDown {



    private static final int TYPE_HOUR = 1, TYPE_DAY = 2;// 倒计时精确类型（天、小时）
    private static final int DEFAULT_TYPE = TYPE_DAY, DEFAULT_PERIOD = 1000,
            DEFAULT_DELAY = 0;// 默认数据

    private int id = 0;
    private int type = DEFAULT_TYPE;// 精确类型-默认小时
    private long endTime;// 结束时间mill
    private Timer timerCountDown;
    private TimeCountDownListener countDownListener;// 刷新
    private long period = DEFAULT_PERIOD;// 周期默认1000毫秒
    private long delay = DEFAULT_DELAY;// 延期默认0毫秒
    private long startTimeMill = -1;// 开始时间毫秒默认当前时间
    private int refreshTimes = 0;// 刷新次数
    public RelativeLayout relativeLayout_Click;//被点击
    public TextView textView_timeDown;//倒计时文本
    public String timeDownFinish = "";
    public boolean isNotListener = false;//是否没有监听器
    public String refresh_start = "";//
    public String refresh_end = "";
    public boolean isShowTimeDown = true;

    public void setIsShowTimeDown(boolean isShowTimeDown) {
        this.isShowTimeDown = isShowTimeDown;
    }

    public void setRelativeLayout_Click(RelativeLayout relativeLayout_Click) {
        this.relativeLayout_Click = relativeLayout_Click;
    }


    public void setRefresh_end(String refresh_end) {
        this.refresh_end = refresh_end;
    }

    public void setRefresh_start(String refresh_start) {
        this.refresh_start = refresh_start;
    }

    public void setisNotListener(boolean isNotListener) {
        this.isNotListener = isNotListener;
    }

    public void setTimeDownFinish(String timeDownFinish) {
        this.timeDownFinish = timeDownFinish;
    }

    private char[] textVule(long value) {
        return String.format("%02d", value).toCharArray();
    }

    /**
     * 倒计时
     *
     * @param type    精确类型
     * @param endTime 结束时间
     * @param period  周期
     * @param delay   延迟
     *                <p>
     *                刷新监听事件
     */
    private TimeCountDown(int type, long startTime, long endTime, long period, long delay, TimeCountDownListener countDownListener) {
        if (type == TYPE_DAY || type == TYPE_HOUR)
            this.type = type;
        this.endTime = endTime;
        this.period = period;
        this.delay = delay;
        this.countDownListener = countDownListener;

        // 开始时间默认当前
        if (startTime < 0)
            startTime = System.currentTimeMillis();
        this.startTimeMill = startTime + delay;
    }

    /**
     * 倒计时
     *
     * @param endTime 结束时间mill
     */
    public TimeCountDown(long startTime, long endTime) {
        this(DEFAULT_TYPE, startTime, endTime, DEFAULT_PERIOD, DEFAULT_DELAY, null);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    /**
     * 开始倒计时
     */
    public void start() {
        if (countDownListener != null)
            countDownListener.onPrepareCountDown();
        timerCountDown = new Timer();
        timerCountDown.scheduleAtFixedRate(timerTaskCountDownTime, delay, period);
    }

    /**
     * 取消倒计时
     */
    public void cancel() {
        refreshTimes = 0;
        timerTaskCountDownTime.cancel();
        if (timerCountDown != null)
            timerCountDown.cancel();
    }

    private TimerTask timerTaskCountDownTime = new TimerTask() {

        @Override
        public void run() {
            Message message = new Message();
            message.what = 1;
            handlerCountDown.sendMessage(message);
        }
    };

    public void setStaticText() {
        long remainMills = endTime - period * refreshTimes
                - startTimeMill;
        long hour = remainMills / (1000 * 60 * 60);// 剩余小时
        long minute = (remainMills % (1000 * 60 * 60)) / (60 * 1000);// 剩余分钟
        long second = (remainMills % (1000 * 60)) / 1000;// 剩余秒
        char[] currentHour = textVule(hour);
        char[] currentSecond = textVule(second);
        char[] currentMinute = textVule(minute);
        if (textView_timeDown != null) {
            textView_timeDown.setText(refresh_start + currentHour[0] + currentHour[1]
                    + "时" + currentMinute[0] + currentMinute[1] + "分" + currentSecond[0] + currentSecond[1] + refresh_end);
        }
    }

    // 抢购商品倒计时的Handler
    private Handler handlerCountDown = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                refreshTimes++;// 刷新次数+1
                // 重现显示剩余时间
                long remainMills = endTime - period * refreshTimes
                        - startTimeMill;

                long day = 0, hour = 0;
                if (type == TYPE_HOUR) {
                    // 精确到小时
                    hour = remainMills / (1000 * 60 * 60);// 剩余小时
                } else if (type == TYPE_DAY) {
                    // 精确到天
                    day = remainMills / (1000 * 60 * 60 * 24);
                    hour = (remainMills % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
                }

                long minute = (remainMills % (1000 * 60 * 60)) / (60 * 1000);// 剩余分钟
                long second = (remainMills % (1000 * 60)) / 1000;// 剩余秒

                if (day <= 0 && hour <= 0 && minute <= 0 && second <= 0) {
                    if (relativeLayout_Click != null) {
                        relativeLayout_Click.setClickable(false);
                    }
                    if (textView_timeDown != null) {
                        textView_timeDown.setText(timeDownFinish);
                        textView_timeDown.setVisibility(View.VISIBLE);
                    }
                    // 倒计时结束
                    if (timerCountDown != null) {
                        timerCountDown.cancel();
                        timerCountDown = null;
                    }

                    if (countDownListener != null) {
                        countDownListener.onFinishCountDown();
                        countDownListener = null;
                    }
                    return;
                }

                if (countDownListener != null) {
                    char[] currentDay = {'0', '0'};
                    char[] currentHour = textVule(hour);
                    char[] currentSecond = textVule(second);
                    char[] currentMinute = textVule(minute);

                    if (type == TYPE_DAY) {
                        // 精确到天
                        currentDay = textVule(day);
                    }
                    countDownListener.onRefreshTime(currentDay, currentHour, currentSecond, currentMinute);
                }
                if (isNotListener) {
                    char[] currentHour = textVule(hour);
                    char[] currentSecond = textVule(second);
                    char[] currentMinute = textVule(minute);
                    if (textView_timeDown != null && isShowTimeDown) {
                        textView_timeDown.setText(refresh_start + currentHour[0] + currentHour[1]
                                + "时" + currentMinute[0] + currentMinute[1] + "分" + currentSecond[0] + currentSecond[1] + refresh_end);
                    }
                }

            }
        }

    };

    public TimeCountDownListener getTimeRefreshListener() {
        return countDownListener;
    }

    public void setTimeRefreshListener(TimeCountDownListener timeRefreshListener) {
        this.countDownListener = timeRefreshListener;
    }

    /**
     * 倒计时监听
     *
     * @author Jiang
     */
    public interface TimeCountDownListener {

        /**
         * 执行前
         */
        void onPrepareCountDown();

        /**
         * 刷新时间执行
         *
         * @param day    剩余天数
         * @param hour   剩余小时数
         * @param minute 剩余分钟数
         * @param second 剩余秒
         */
        void onRefreshTime(char[] day, char[] hour, char[] minute, char[] second);

        /**
         * 倒计时结束
         */
        void onFinishCountDown();
    }
}
